<template>
  <div class="flex-1 flex flex-col h-full relative transition-colors duration-300"
       :class="themeStore.theme.bg.primary">

    <!-- 消息区域 - GPT官网风格 -->
    <div class="flex-1 overflow-y-auto px-4 py-3 pb-32 chat-messages" ref="messagesContainer">
      <div class="max-w-4xl mx-auto">
      <!-- 欢迎消息 - 紧凑版 -->
      <div v-if="messages.length === 0" class="flex flex-col items-center justify-center h-full text-center">
        <div class="w-8 h-8 bg-indigo-600 rounded-full flex items-center justify-center mb-2">
          <font-awesome-icon :icon="['fas', 'heart']" class="text-white text-sm" />
        </div>
        <h2 class="text-base font-bold mb-1" :class="themeStore.theme.text.primary">欢迎使用心理健康助手</h2>
        <p class="mb-3 max-w-sm text-xs" :class="themeStore.theme.text.tertiary">
          我是您的专业心理健康助手，可以为您提供情感支持、心理咨询建议和日常心理健康指导。请随时与我分享您的想法和感受。
        </p>
        <div v-if="!isLoggedIn" class="mb-3 p-2 rounded-lg transition-colors duration-300"
             :class="[
               themeStore.isDark ? 'bg-yellow-900/30 border border-yellow-600/50' : 'bg-yellow-50 border border-yellow-200'
             ]">
          <p class="text-xs" :class="themeStore.isDark ? 'text-yellow-400' : 'text-yellow-700'">
            <font-awesome-icon :icon="['fas', 'info-circle']" class="mr-1" />
            您当前处于未登录状态，对话内容不会被保存。登录后可保存对话记录。
          </p>
        </div>
        
        <!-- 快速开始建议 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-1.5 max-w-lg">
          <button
            v-for="suggestion in quickSuggestions"
            :key="suggestion.text"
            @click="sendQuickMessage(suggestion.text)"
            class="p-2 rounded-lg transition-all duration-200 text-left group"
            :class="[
              themeStore.theme.bg.tertiary,
              themeStore.theme.border.primary,
              themeStore.theme.hover,
              'border hover:border-indigo-500'
            ]"
          >
            <div class="flex items-center space-x-1.5">
              <div class="w-5 h-5 bg-indigo-600 rounded-full flex items-center justify-center group-hover:bg-indigo-500 transition-colors duration-200">
                <font-awesome-icon :icon="suggestion.icon" class="text-white text-xs" />
              </div>
              <div>
                <p class="font-medium text-xs" :class="themeStore.theme.text.primary">{{ suggestion.title }}</p>
                <p class="text-xs" :class="themeStore.theme.text.tertiary">{{ suggestion.description }}</p>
              </div>
            </div>
          </button>
        </div>
      </div>

      <!-- 消息列表 - 紧凑版 -->
      <div v-else class="space-y-3">
        <div
          v-for="(message, index) in messages"
          :key="message.id || index"
          class="flex"
          :class="message.role === 'user' ? 'justify-end' : 'justify-start'"
        >
          <!-- 思考过程区块 - 累积显示版本 -->
          <div v-if="message.role === 'system' && message.type === 'thinking_block'" class="w-full">
            <ThinkingBlock
              :thinking-steps="message.thinkingSteps || []"
              :detailed-content="message.detailedContent || ''"
              :all-thinking-content="message.allThinkingContent?.value || message.allThinkingContent || ''"
              :thinking-iterations="message.thinkingIterations?.value || message.thinkingIterations || []"
              :is-thinking="message.isThinking || false"
              :default-collapsed="false"
            />
          </div>

          <!-- 系统消息 - 过滤掉status类型的消息 -->
          <div v-else-if="message.role === 'system' && message.type !== 'status'" class="flex space-x-3 w-full"
               :class="{
                 'mb-3': !message.isCompact,
                 'mb-1': message.isCompact
               }">
            <div class="flex-shrink-0">
              <div class="rounded-sm flex items-center justify-center"
                   :class="{
                     'w-7 h-7 bg-yellow-600': message.type === 'status' || message.type === 'tools_status',
                     'w-5 h-5 bg-purple-600': message.type === 'thinking' && message.isCompact,
                     'w-7 h-7 bg-purple-600': message.type === 'thinking' && !message.isCompact
                   }">
                <font-awesome-icon
                  :icon="message.type === 'thinking' ? ['fas', 'brain'] : ['fas', 'cog']"
                  :class="message.type === 'thinking' ? 'animate-pulse' : 'animate-spin'"
                  class="text-white"
                  :style="{ fontSize: message.isCompact ? '10px' : '12px' }" />
              </div>
            </div>
            <div class="flex-1 min-w-0">
              <div class="rounded-lg border-l-4"
                   :class="{
                     'p-3 bg-yellow-900/20 border-yellow-500 text-yellow-200': message.type === 'status' || message.type === 'tools_status',
                     'p-1.5 bg-purple-900/10 border-purple-500 text-purple-300': message.type === 'thinking' && message.isCompact,
                     'p-3 bg-purple-900/20 border-purple-500 text-purple-200': message.type === 'thinking' && !message.isCompact
                   }">
                <div class="leading-4 whitespace-pre-wrap"
                     :class="{
                       'text-xs': !message.isCompact,
                       'text-xs italic': message.isCompact
                     }">{{ message.displayText?.value || message.displayText || message.content?.value || message.content }}</div>
              </div>
              <div v-if="!message.isCompact" class="mt-1">
                <span class="text-xs text-gray-500">{{ formatTime(message.timestamp) }}</span>
              </div>
            </div>
          </div>

          <!-- 助手消息 - GPT官网风格 -->
          <div v-else-if="message.role === 'assistant'" class="flex space-x-3 mb-5">
            <div class="flex-shrink-0">
              <div class="w-7 h-7 bg-green-600 rounded-sm flex items-center justify-center">
                <font-awesome-icon :icon="['fas', 'robot']" class="text-white text-xs" />
              </div>
            </div>
            <div class="flex-1 min-w-0">
              <div class="prose prose-invert max-w-none">
                <div v-html="formatMessage(message.displayText?.value || message.displayText || message.content?.value || message.content)"
                     class="whitespace-pre-wrap text-xs leading-4"
                     :class="themeStore.theme.text.primary"></div>
              </div>
              <div class="flex items-center justify-between mt-2">
                <span class="text-xs" :class="themeStore.theme.text.muted">{{ formatTime(message.created_at) }}</span>
                <div class="flex items-center space-x-1.5">
                  <button
                    @click="copyMessage(message.content)"
                    class="p-1.5 rounded transition-colors duration-200"
                    :class="[
                      themeStore.theme.text.muted,
                      themeStore.theme.hover,
                      'hover:text-gray-300'
                    ]"
                    title="复制消息"
                  >
                    <font-awesome-icon :icon="['fas', 'copy']" class="h-3.5 w-3.5" />
                  </button>
                  <button
                    @click="likeMessage(getMessageId(message), true)"
                    class="p-1.5 rounded transition-colors duration-200 hover:text-green-400"
                    :class="[
                      themeStore.theme.text.muted,
                      themeStore.theme.hover,
                      { 'text-green-400': message.feedback === 1 || message.feedback === 'positive' }
                    ]"
                    title="有帮助"
                    :disabled="!getMessageId(message)"
                  >
                    <font-awesome-icon :icon="['fas', 'thumbs-up']" class="h-3.5 w-3.5" />
                  </button>
                  <button
                    @click="likeMessage(getMessageId(message), false)"
                    class="p-1.5 rounded transition-colors duration-200 hover:text-red-400"
                    :class="[
                      themeStore.theme.text.muted,
                      themeStore.theme.hover,
                      { 'text-red-400': message.feedback === -1 || message.feedback === 'negative' }
                    ]"
                    title="没有帮助"
                    :disabled="!getMessageId(message)"
                  >
                    <font-awesome-icon :icon="['fas', 'thumbs-down']" class="h-3.5 w-3.5" />
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- 用户消息 - 右对齐风格 -->
          <div v-else class="flex space-x-3 mb-5 max-w-2xl ml-auto">
            <div class="text-right">
              <div class="inline-block bg-blue-600 text-white px-3 py-2 rounded-lg max-w-xs lg:max-w-md text-xs leading-4">{{ message.content }}</div>
              <div class="flex justify-end mt-2">
                <span class="text-xs" :class="themeStore.theme.text.muted">{{ formatTime(message.created_at) }}</span>
              </div>
            </div>
            <div class="flex-shrink-0">
              <div class="w-7 h-7 bg-blue-600 rounded-full flex items-center justify-center">
                <font-awesome-icon :icon="['fas', 'user']" class="text-white text-xs" />
              </div>
            </div>
          </div>
        </div>

        <!-- 正在输入指示器 - 只在真正思考时显示，不在最终答案流式输出时显示 -->
        <div v-if="isLoading && isCurrentlyThinking" class="flex space-x-3 mb-5">
          <div class="flex-shrink-0">
            <div class="w-7 h-7 bg-green-600 rounded-sm flex items-center justify-center">
              <font-awesome-icon :icon="['fas', 'robot']" class="text-white text-xs" />
            </div>
          </div>
          <div class="flex-1 min-w-0">
            <div class="flex items-center space-x-2">
              <div class="flex space-x-1">
                <div class="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce"></div>
                <div class="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0.1s"></div>
                <div class="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0.2s"></div>
              </div>
              <span class="text-gray-400 text-sm">正在思考中...</span>
            </div>
          </div>
        </div>
      </div>
      </div>
    </div>

    <!-- 输入区域 - GPT官网风格 -->
        <div class="fixed bottom-0 left-0 right-0 border-t px-3 py-2 z-40 transition-colors duration-300"
             :class="[
               themeStore.theme.bg.primary,
               themeStore.theme.border.primary,
               { 'md:left-60': !sidebarCollapsed, 'md:left-0': sidebarCollapsed }
             ]">
           <div class="max-w-lg mx-auto">
        <form @submit.prevent="handleSendMessage" class="relative">
          <div class="relative flex items-end rounded-xl border transition-colors"
               :class="[
                 themeStore.theme.input.bg,
                 themeStore.theme.input.border,
                 'focus-within:border-gray-500'
               ]">
            <textarea
              v-model="inputMessage"
              ref="messageInput"
              @keydown="handleKeyDown"
              placeholder="请输入您的问题或想法..."
              class="flex-1 px-3 py-2.5 bg-transparent focus:outline-none resize-none text-xs leading-4 transition-all duration-200"
              :class="[
                themeStore.theme.input.text,
                themeStore.theme.input.placeholder
              ]"
              rows="1"
              :disabled="isLoading"
              style="min-height: 52px; max-height: 200px;"
            ></textarea>
            
            <!-- 发送按钮 -->
            <button
              type="submit"
              :disabled="isLoading || !inputMessage.trim() || inputMessage.length > 2000"
              class="m-1.5 p-1.5 rounded-lg transition-colors duration-200 flex items-center justify-center"
              :class="[
                themeStore.isDark
                  ? 'bg-white hover:bg-gray-100 disabled:bg-gray-600 text-gray-900 disabled:text-gray-400'
                  : 'bg-gray-900 hover:bg-gray-800 disabled:bg-gray-300 text-white disabled:text-gray-500',
                'disabled:cursor-not-allowed'
              ]"
              title="发送消息"
            >
              <font-awesome-icon
                :icon="isLoading ? ['fas', 'spinner'] : ['fas', 'arrow-up']"
                :class="{ 'animate-spin': isLoading }"
                class="h-3.5 w-3.5"
              />
            </button>
          </div>

          <!-- 字符计数 -->
          <div class="absolute -bottom-5 right-0 text-xs" :class="themeStore.theme.text.muted" v-if="inputMessage.length > 1800">
            {{ inputMessage.length }}/2000
          </div>
        </form>

        <!-- 输入提示 -->
            <div class="mt-2 text-xs text-center" :class="themeStore.theme.text.muted">
              AI 可能会出错。请核查重要信息。
            </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, nextTick, watch, defineExpose } from 'vue'
import MarkdownIt from 'markdown-it'
import api from '../api/index.js'
import ThinkingBlock from './ThinkingBlock.vue'
import { useThemeStore } from '../stores/theme'

// 配置markdown-it - 增强版
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  breaks: true
})

// 添加自定义渲染规则
md.renderer.rules.fence = function (tokens, idx, options, env, renderer) {
  const token = tokens[idx]
  const info = token.info ? md.utils.unescapeAll(token.info).trim() : ''
  const langName = info ? info.split(/\s+/g)[0] : ''

  return `<div class="code-block-container my-4">
    ${langName ? `<div class="code-block-header bg-gray-700 px-3 py-1 text-xs text-gray-300 rounded-t-lg border-b border-gray-600">${langName}</div>` : ''}
    <pre class="bg-gray-800 p-4 rounded-${langName ? 'b' : ''}lg overflow-x-auto border border-gray-600"><code class="text-green-300 text-sm font-mono">${md.utils.escapeHtml(token.content)}</code></pre>
  </div>`
}

// 自定义表格渲染
md.renderer.rules.table_open = function () {
  return '<div class="table-container overflow-x-auto my-4"><table class="w-full border-collapse border border-gray-600 rounded-lg overflow-hidden">'
}

md.renderer.rules.table_close = function () {
  return '</table></div>'
}

export default {
  name: 'ChatArea',
  components: {
    ThinkingBlock
  },
  props: {
    currentConversation: {
      type: Object,
      default: null
    },
    messages: {
      type: Array,
      default: () => []
    },
    isLoading: {
      type: Boolean,
      default: false
    },
    isCurrentlyThinking: {
      type: Boolean,
      default: false
    },
    isLoggedIn: {
      type: Boolean,
      default: false
    },
    sidebarCollapsed: {
      type: Boolean,
      default: false
    }
  },
  emits: ['sendMessage', 'feedbackUpdated'],
  setup(props, { emit }) {
    // 主题管理
    const themeStore = useThemeStore()

    const inputMessage = ref('')
    const messagesContainer = ref(null)
    const messageInput = ref(null)
    
    const quickSuggestions = ref([
      {
        icon: ['fas', 'heart'],
        title: '情感支持',
        description: '分享您的感受和情绪',
        text: '我最近感到有些焦虑，能帮我分析一下原因吗？'
      },
      {
        icon: ['fas', 'brain'],
        title: '压力管理',
        description: '学习应对压力的方法',
        text: '我工作压力很大，有什么好的减压方法吗？'
      },
      {
        icon: ['fas', 'moon'],
        title: '睡眠问题',
        description: '改善睡眠质量',
        text: '我最近失眠严重，有什么改善睡眠的建议吗？'
      },
      {
        icon: ['fas', 'users'],
        title: '人际关系',
        description: '处理人际交往困扰',
        text: '我在人际交往中遇到了一些困难，能给我一些建议吗？'
      }
    ])
    
    const handleSendMessage = () => {
      if (!inputMessage.value.trim() || props.isLoading) return
      
      emit('sendMessage', inputMessage.value.trim())
      inputMessage.value = ''
      
      // 重置输入框高度
      nextTick(() => {
        if (messageInput.value) {
          messageInput.value.style.height = '44px'
        }
      })
    }
    
    const sendQuickMessage = (message) => {
      emit('sendMessage', message)
    }
    
    const handleKeyDown = (event) => {
      if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault()
        handleSendMessage()
      }
      
      // 自动调整输入框高度
      nextTick(() => {
        const textarea = event.target
        textarea.style.height = '44px'
        textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'
      })
    }
    
    // 🔥 Vue3最佳实践：自动滚动到底部
    const scrollToBottom = async (smooth = false) => {
      await nextTick() // 等待DOM更新
      if (messagesContainer.value) {
        if (smooth) {
          messagesContainer.value.scrollTo({
            top: messagesContainer.value.scrollHeight,
            behavior: 'smooth'
          })
        } else {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
        }
      }
    }
    
    const formatMessage = (content) => {
      try {
        // 预处理内容，彻底清理多余的空行和格式问题
        let cleanContent = content
          // 移除所有多余的空行（2个或以上连续换行变为1个）
          .replace(/\n{2,}/g, '\n')
          // 移除行首行尾的空白字符
          .replace(/^\s+|\s+$/gm, '')
          // 移除空行中的空白字符
          .replace(/^\s*$/gm, '')
          // 确保列表项前有换行，但不要多余的空行
          .replace(/([^\n])(\d+\.\s)/g, '$1\n$2')
          .replace(/([^\n])(•\s)/g, '$1\n$2')
          // 确保标题前有换行，但不要多余的空行
          .replace(/([^\n])(#{1,6}\s)/g, '$1\n$2')
          // 移除连续的空行
          .replace(/\n\s*\n/g, '\n')
          // 移除开头和结尾的多余换行
          .trim()
          // 最后再次清理连续换行
          .replace(/\n+/g, '\n')

        // 使用markdown-it渲染
        let html = md.render(cleanContent)

        // 彻底清理渲染后的HTML
        html = html
          // 移除空段落（各种形式）
          .replace(/<p>\s*<\/p>/g, '')
          .replace(/<p><\/p>/g, '')
          .replace(/<p>\s*&nbsp;\s*<\/p>/g, '')
          .replace(/<p>\s*<br\s*\/?>\s*<\/p>/g, '')
          // 移除连续的<br>标签
          .replace(/(<br\s*\/?>){2,}/g, '<br>')
          // 移除段落间多余的<br>
          .replace(/<\/p>\s*<br\s*\/?>\s*<p>/g, '</p><p>')
          // 移除列表项间多余的<br>
          .replace(/<\/li>\s*<br\s*\/?>\s*<li>/g, '</li><li>')
          // 移除标题后的<br>
          .replace(/<\/h[1-6]>\s*<br\s*\/?>/g, '</h1>')
          .replace(/<\/h([1-6])>\s*<br\s*\/?>/g, '</h$1>')
          // 移除多余的空白字符和换行
          .replace(/\s+/g, ' ')
          .replace(/>\s+</g, '><')
          .trim()

        // 添加自定义样式类 - 优化版
        html = html
          // 为列表添加样式 - 紧凑间距
          .replace(/<ul>/g, '<ul class="list-disc list-inside space-y-0 ml-4 my-1">')
          .replace(/<ol>/g, '<ol class="list-decimal list-inside space-y-0 ml-4 my-1">')
          .replace(/<li>/g, '<li class="text-gray-100 leading-tight py-0.5">')

          // 为标题添加样式 - 紧凑间距
          .replace(/<h1>/g, '<h1 class="text-xl font-bold text-white mb-1 mt-2 pb-1 border-b border-gray-600">')
          .replace(/<h2>/g, '<h2 class="text-lg font-bold text-blue-300 mb-1 mt-2">')
          .replace(/<h3>/g, '<h3 class="text-base font-semibold text-green-300 mb-0.5 mt-1">')
          .replace(/<h4>/g, '<h4 class="text-sm font-semibold text-yellow-300 mb-0.5 mt-1">')

          // 为段落添加样式 - 紧凑间距
          .replace(/<p>/g, '<p class="text-gray-100 mb-1 leading-tight">')

          // 为强调文本添加样式
          .replace(/<strong>/g, '<strong class="font-semibold text-white bg-gray-700 px-1 py-0.5 rounded">')
          .replace(/<em>/g, '<em class="italic text-blue-300 font-medium">')

          // 为代码块添加样式
          .replace(/<code>/g, '<code class="bg-gray-700 text-green-300 px-1 py-0.5 rounded text-sm font-mono">')
          .replace(/<pre>/g, '<pre class="bg-gray-800 p-3 rounded-lg overflow-x-auto my-2 border border-gray-600">')

          // 为引用块添加样式
          .replace(/<blockquote>/g, '<blockquote class="border-l-4 border-blue-500 pl-3 py-1 my-2 bg-gray-800 rounded-r-lg">')

          // 为表格添加样式
          .replace(/<table>/g, '<table class="w-full border-collapse border border-gray-600 my-2 rounded-lg overflow-hidden">')
          .replace(/<th>/g, '<th class="border border-gray-600 px-2 py-1 bg-gray-700 text-white font-semibold text-left text-sm">')
          .replace(/<td>/g, '<td class="border border-gray-600 px-2 py-1 text-gray-100 text-sm">')

          // 为分隔线添加样式
          .replace(/<hr>/g, '<hr class="my-3 border-gray-600">')

          // 为特殊符号添加样式
          .replace(/✓/g, '<span class="text-green-400 font-bold">✓</span>')
          .replace(/❌/g, '<span class="text-red-400 font-bold">❌</span>')
          .replace(/⚠️/g, '<span class="text-yellow-400 font-bold">⚠️</span>')
          .replace(/💡/g, '<span class="text-blue-400 font-bold">💡</span>')
          .replace(/🎯/g, '<span class="text-purple-400 font-bold">🎯</span>')
          .replace(/🔧/g, '<span class="text-orange-400 font-bold">🔧</span>')

          // 为链接添加样式
          .replace(/<a /g, '<a class="text-blue-400 hover:text-blue-300 underline" target="_blank" ')

          // 为特殊格式添加样式
          .replace(/\*\*\*(.*?)\*\*\*/g, '<span class="font-bold text-yellow-300 bg-yellow-900 bg-opacity-30 px-1 py-0.5 rounded">$1</span>')

          // 为数字列表项添加特殊样式
          .replace(/<li class="text-gray-100 leading-normal">(\d+\.)/g, '<li class="text-gray-100 leading-normal"><span class="font-semibold text-blue-300">$1</span>')

        return html
      } catch (error) {
        console.error('Markdown渲染错误:', error)
        // 降级到简单渲染
        return content
          // 清理多余空行
          .replace(/\n{3,}/g, '\n\n')
          .trim()
          // 简单markdown处理
          .replace(/\*\*(.*?)\*\*/g, '<strong class="font-semibold text-white">$1</strong>')
          .replace(/\*(.*?)\*/g, '<em class="italic text-blue-300">$1</em>')
          .replace(/`(.*?)`/g, '<code class="bg-gray-700 text-green-300 px-1 rounded text-sm">$1</code>')
          .replace(/### (.*?)$/gm, '<h3 class="text-base font-semibold text-green-300 mb-1 mt-2">$1</h3>')
          .replace(/## (.*?)$/gm, '<h2 class="text-lg font-bold text-blue-300 mb-2 mt-3">$1</h2>')
          .replace(/# (.*?)$/gm, '<h1 class="text-xl font-bold text-white mb-2 mt-4">$1</h1>')
          .replace(/\n\n/g, '<br><br>')
          .replace(/\n/g, '<br>')
      }
    }
    
    const formatTime = (timestamp) => {
      if (!timestamp) return ''
      
      const date = new Date(timestamp)
      const now = new Date()
      const diffMs = now - date
      const diffMins = Math.floor(diffMs / 60000)
      
      if (diffMins < 1) return '刚刚'
      if (diffMins < 60) return `${diffMins}分钟前`
      if (diffMins < 1440) return `${Math.floor(diffMins / 60)}小时前`
      
      return date.toLocaleString('zh-CN', {
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    const copyMessage = async (content) => {
      try {
        await navigator.clipboard.writeText(content)
        // TODO: 显示复制成功提示
        console.log('消息已复制到剪贴板')
      } catch (err) {
        console.error('复制失败:', err)
      }
    }
    
    // 安全获取消息ID的函数
    const getMessageId = (message) => {
      // 尝试多种可能的ID字段
      const id = message.message_id || message.id || message.messageId
      console.log('🔍 [Feedback] 获取消息ID:', {
        message_id: message.message_id,
        id: message.id,
        messageId: message.messageId,
        selected: id,
        role: message.role,
        type: message.type
      })
      return id
    }

    const likeMessage = async (messageId, isPositive) => {
      try {
        console.log('🔍 [Feedback] 消息反馈:', messageId, isPositive ? 'positive' : 'negative')

        // 检查messageId是否有效
        if (!messageId || messageId === 'undefined') {
          console.error('❌ [Feedback] 无效的消息ID:', messageId)
          return
        }

        // 调用API更新消息反馈
        const feedback = isPositive ? 1 : -1
        
        // 立即更新本地消息状态，提供即时反馈
        const targetMessage = props.messages.find(msg => msg.message_id === messageId)
        if (targetMessage) {
          targetMessage.feedback = feedback
        }
        
        const response = await api.updateMessageFeedback(messageId, feedback)
        
        if (response.data) {
          console.log('反馈更新成功:', response.data)
          // 确保本地状态与API返回的数据一致
          if (targetMessage && response.data.feedback !== undefined) {
            targetMessage.feedback = response.data.feedback
          }
          // 触发消息列表更新，让父组件重新获取消息
          emit('feedbackUpdated', messageId, feedback)
        }
      } catch (error) {
        console.error('更新消息反馈失败:', error)
        // 如果API调用失败，恢复本地状态
        const targetMessage = props.messages.find(msg => msg.message_id === messageId)
        if (targetMessage) {
          targetMessage.feedback = null
        }
        // TODO: 显示错误提示
      }
    }
    
    const clearChat = () => {
      if (confirm('确定要清空当前对话吗？此操作无法撤销。')) {
        // TODO: 实现清空对话功能
        console.log('清空对话')
      }
    }
    
    const exportChat = () => {
      // TODO: 实现导出对话功能
      console.log('导出对话')
    }
    
    // 🔥 Vue3最佳实践：监听messages变化，自动滚动到底部
    watch(
      () => props.messages,
      async () => {
        await scrollToBottom() // 使用async/await确保时序
      },
      { deep: true, flush: 'post' }
    )

    // 🔥 额外监听：监听消息内容的变化（流式输出时）
    watch(
      () => props.messages.map(m => ({
        content: m.content,
        displayText: m.displayText,
        thinkingContent: m.thinkingContent || m.detailedContent?.value || '',
        allThinkingContent: m.allThinkingContent?.value || m.allThinkingContent || '',
        thinkingStepsLength: m.thinkingSteps?.length || 0
      })),
      async () => {
        await scrollToBottom() // 内容变化时也自动滚动
      },
      { deep: true, flush: 'post' }
    )

    // 🔥 Vue3最佳实践：暴露方法给父组件
    defineExpose({
      scrollToBottom
    })

    return {
      themeStore,
      inputMessage,
      messagesContainer,
      messageInput,
      quickSuggestions,
      handleSendMessage,
      sendQuickMessage,
      handleKeyDown,
      formatMessage,
      formatTime,
      copyMessage,
      getMessageId,
      likeMessage,
      clearChat,
      exportChat,
      scrollToBottom // 也在return中包含，以便模板使用
    }
  }
}
</script>

<style scoped>
/* 自定义滚动条样式 */
.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: #374151;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background: #6B7280;
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background: #9CA3AF;
}

/* Markdown内容样式 */
:deep(.prose) {
  @apply max-w-none;
}

:deep(.prose h1) {
  @apply text-xl font-bold text-white mb-3 mt-4;
}

:deep(.prose h2) {
  @apply text-lg font-bold text-white mb-2 mt-3;
}

:deep(.prose h3) {
  @apply text-base font-semibold text-white mb-2 mt-2;
}

:deep(.prose p) {
  @apply text-gray-100 mb-2 leading-relaxed;
}

:deep(.prose ul) {
  @apply list-disc list-inside space-y-1 ml-4 mb-3;
}

:deep(.prose ol) {
  @apply list-decimal list-inside space-y-1 ml-4 mb-3;
}

:deep(.prose li) {
  @apply text-gray-100 leading-relaxed;
}

:deep(.prose strong) {
  @apply font-semibold text-white;
}

:deep(.prose em) {
  @apply italic text-blue-300;
}

:deep(.prose code) {
  @apply bg-gray-700 text-green-300 px-1 py-0.5 rounded text-sm;
}

:deep(.prose pre) {
  @apply bg-gray-800 p-3 rounded-lg overflow-x-auto my-2;
}

:deep(.prose pre code) {
  @apply bg-transparent p-0;
}

:deep(.prose a) {
  @apply text-blue-400 hover:text-blue-300 underline;
}

:deep(.prose blockquote) {
  @apply border-l-4 border-gray-600 pl-4 italic text-gray-300 my-2;
}

/* 特殊符号样式 */
:deep(.text-green-400) {
  @apply font-bold;
}

/* 输入框样式 */
textarea {
  field-sizing: content;
}
</style>